<template>
    <article class="divCommon w-full bg-white  shadow-md rounded-lg p-6 text-center transition-transform duration-300">
        <h1 class="text-2xl font-bold text-primary mb-2" id="title">{{ props.data.title }}</h1>
        <div class="mt-2 text-gray-600">
            <i class="iconfont icon-time">发布于{{ props.data.updateTime }}</i>
        </div>
        <div class="mt-5 text-left">
            <p class="text-gray-800 leading-relaxed mb-4">
                <v-md-preview :text="data.content" @rendered="handleTOC" ref="preview"></v-md-preview>
            </p>
            <n-tag v-for="tag in props.data.tags" size="small"
                class="!bg-blue-50 !text-blue-700 !border-blue-200 rounded-lg px-2">
                #{{ tag }}
            </n-tag>
            <!-- <p v-for="item in props.data.tags">#{{ item }}</p> -->
        </div>
    </article>
</template>

<script setup lang="ts">
import { onMounted, defineProps, defineEmits, nextTick, watch,ref } from 'vue';
import { parseMarkdownHeadings } from '@/utils/markdown';
import VMdPreview from '@kangc/v-md-editor/lib/preview';
const emit = defineEmits(['toc-ready']);
const titles = ref([]);
const preview = ref();
const heading = ref()
const rootFontSize = ref(0);

// 获取根元素的 font-size
onMounted(() => {
    rootFontSize.value = parseFloat(
        window.getComputedStyle(document.documentElement).fontSize
    );
});
interface ArticleContentProps {
    articleId: number;
    authorId: number;
    content: string;
    tags: string;
    title: string;
    titleImg: string;
    updateTime: string;
};
const props = defineProps({
    data: {
        type: Object as () => ArticleContentProps,
        required: true,
        default: ''
    },
    toc: {
        type: Object as () => { text: string; id: string; level: number },
        default: () => []
    }
})
 const handleTOC = () => {
     // 等待 DOM 更新
    nextTick(() => {
        const anchors = parseMarkdownHeadings(props.data.content);
        emit('toc-ready', anchors);
    });
};
const remToPixels = (remString:string) => {
    const remValue = parseFloat(remString); // 提取数字部分
    if (isNaN(remValue)) {
        throw new Error('Invalid rem value');
    }
    return remValue * rootFontSize.value;
}
watch(() => props.data, (newVal) => {
    // 当内容更新后处理目录
    handleTOC();
}, { immediate: true });
watch(() => props.toc, (newVal) => {
    if (props.data && preview.value) {
        heading.value = preview.value.$el.querySelector(
            `[data-v-md-heading="${newVal.id}"]`
        );
        preview.value.scrollToTarget({
          target: heading.value,
          scrollContainer: window,
            top: remToPixels('5rem'),
        });
    }
    
}, { immediate: true });
</script>

<style scoped>
:deep(.github-markdown-body){
    padding: 0;
}
</style>